package com.example.ruiji.filter;

import com.alibaba.fastjson.JSON;
import com.example.ruiji.common.Result;
import com.example.ruiji.common.ThreadLocalId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
@Component
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Autowired
    HttpSession httpSession;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        //如果登录了，就放行
        Long employeeId = (Long) httpServletRequest.getSession().getAttribute("employee");
        if (employeeId != null) {
            ThreadLocalId.setId(employeeId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        Long userId = (Long) httpServletRequest.getSession().getAttribute("userId");
        if (userId != null) {
            ThreadLocalId.setId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //如果是登录接口，就放行
        if (checkURL(urls, requestURI)) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean checkURL(String[] URLS, String requestURI) {
        for (String url : URLS) {
            if (PATH_MATCHER.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
